﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using ServBus.ListForm2010.Setup.Utilities;

namespace ServBus.ListForm2010.Setup.Commands
{
    class DeploySolutionCmd : BaseCommand
    {
        private bool IsLocalDeploy()
        {
            return ((SPServer.LocalServerRole == SPServerRole.SingleServer) ||
                (SPFarm.Local.TimerService.Instances.Count == 1));
        }

        public override string Description
        {
            get { return Properties.Resources.CmdDeploySolution; }
        }

        public override bool Execute()
        {
            try
            {
                
                Log.WriteLog(Log.LogType.Info, "Starting Deploying Solution...");
                SPSolution solution = SPFarm.Local.Solutions[Constants.WSPNAME];
                Collection<SPWebApplication> webapps = new Collection<SPWebApplication>();
                foreach (SPWebApplication webapp in SPWebService.AdministrationService.WebApplications)
                    webapps.Add(webapp);
                if (IsLocalDeploy())
                {
                    solution.DeployLocal(true, webapps, true);
                }
                else
                {
                    solution.Deploy(DateTime.Now.AddHours(-1), true, webapps, true);
                }
                Log.WriteLog(Log.LogType.Info, "Solution Deployed.");
                return true;
            }
            catch (Exception ex)
            {
                Log.WriteLog(Log.LogType.Error, "Deploy Solution Error. " + ex.GetType().FullName + ". " + ex.Message);
                return false;
            }
        }

        public override bool Rollback()
        {
            return new RetractSolutionCmd().Execute();
        }
    }
}
